﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Threading;
using System.Timers;
using System.Web;
using System.IO;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.WebUI
{
	/// <summary>
	/// 应用程序 Global.asax 的基类。
	/// </summary>
	public class Global : System.Web.HttpApplication
	{
		private Object thisLock = new Object();

		/// <summary>
		/// 启动 Sql 缓存依赖。
		/// </summary>
		/// <returns></returns>
		protected bool StartSqlDependency()
		{
			bool b = true;
			try
			{
				lock (thisLock)
				{
					GenericModuleDataContext dc = new GenericModuleDataContext();
					//dc.ExecuteCommand(@"ALTER DATABASE [" + dc.Connection.Database + "] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;");
					SqlDependency.Start(dc.Connection.ConnectionString);
					dc.Dispose();
				}
			}
			catch (Exception err)
			{
				b = false;
			}
			return b;
		}

		/// <summary>
		/// 结束 Sql 缓存依赖。
		/// </summary>
		/// <returns></returns>
		protected bool EndSqlDependency()
		{
			bool b = true;
			try
			{
				lock (thisLock)
				{
					GenericModuleDataContext dc = new GenericModuleDataContext();
					SqlDependency.Stop(dc.Connection.ConnectionString);
					dc.Dispose();
				}
			}
			catch (Exception err)
			{
				b = false;
			}
			return b;
		}




		/// <summary>
		/// 是否成功初始化了 Sql 缓存依赖。
		/// </summary>
		private static bool IsInitSqlDependency = false;

		protected virtual void Application_Start(object sender, EventArgs e)
		{
			IsInitSqlDependency = StartSqlDependency();
		}

		protected virtual void Application_BeginRequest(object sender, EventArgs e)
		{
			if (!IsInitSqlDependency)
			{
				IsInitSqlDependency = StartSqlDependency();
			}
		}

		protected virtual void Application_End(object sender, EventArgs e)
		{
			IsInitSqlDependency = !EndSqlDependency();
		}
	}




	public class SiteGlobal : Global
	{
		protected override void Application_Start(object sender, EventArgs e)
		{
			base.Application_Start(sender, e);
			StartBuildCachePage();
		}

		protected override void Application_End(object sender, EventArgs e)
		{
			StopBuildCachePage();
			base.Application_End(sender, e);
		}



		private static System.Timers.Timer BuildCachePageTimer;
		private static readonly int BuildCachePageInterval = IntExtensions.ParseOrDefault(ConfigurationManager.AppSettings["AutoBuildCachePageInterval"], 0);
		private static void StartBuildCachePage()
		{
			if (BuildCachePageInterval <= 0) return;

			if (BuildCachePageTimer != null)
			{
				BuildCachePageTimer.Close();
				BuildCachePageTimer.Dispose();
				BuildCachePageTimer = null;
			}

			BuildCachePageTimer = new System.Timers.Timer(BuildCachePageInterval);
			BuildCachePageTimer.Elapsed += new ElapsedEventHandler(BuildCachePageTimer_Elapsed);
			BuildCachePageTimer.Enabled = true;
			BuildCachePageTimer.AutoReset = false;
		}

		private static void StopBuildCachePage()
		{
			if (BuildCachePageTimer != null)
			{
				BuildCachePageTimer.Close();
				BuildCachePageTimer.Dispose();
				BuildCachePageTimer = null;
			}
		}

		private static void BuildCachePageTimer_Elapsed(object source, ElapsedEventArgs e)
		{
			try
			{
				CachePages.BuildCachePage(Sites.CurrentSiteId, true);

				LogBuildCachePage("成功创建缓存页。");
			}
			catch (Exception err)
			{
				LogBuildCachePage(err.Message);
			}

			StartBuildCachePage();
		}

		private static void LogBuildCachePage(string message)
		{
			string path = HttpRuntime.AppDomainAppPath;
			path += CachePages.AutoBuildLogFileName;

			lock (path)
			{
				var writer = File.AppendText(path);
				message = DateTime.Now + "\n" + message + "\n\n";
				writer.Write(message);
				writer.Close();
				writer.Dispose();
			}
		}
	}
}